package com.youxin.third.auth.oauth2.process;

import com.youxin.third.auth.oauth2.process.validator.CustomAuthorizationCodeValidator;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.as.validator.ClientCredentialValidator;
import org.apache.oltu.oauth2.as.validator.PasswordValidator;
import org.apache.oltu.oauth2.as.validator.RefreshTokenValidator;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.apache.oltu.oauth2.common.utils.OAuthUtils;
import org.apache.oltu.oauth2.common.validators.OAuthValidator;

import javax.servlet.http.HttpServletRequest;

/**
 * 2015/7/3
 * <p/>
 * Ext  OAuthTokenRequest
 *
 * @author Shengzhao Li
 */
public class OAuthTokenxRequest extends OAuthTokenRequest {

    /**
     * Create an OAuth Token request from a given HttpSerlvetRequest
     *
     * @param request the httpservletrequest that is validated and transformed into the OAuth Token Request
     * @throws OAuthSystemException  if an unexpected exception was thrown
     * @throws OAuthProblemException if the request was not a valid Token request this exception is thrown.
     */
    public OAuthTokenxRequest(HttpServletRequest request) throws OAuthSystemException, OAuthProblemException {
        super(request);
    }

    public HttpServletRequest request() {
        return this.request;
    }


    @Override
    protected OAuthValidator<HttpServletRequest> initValidator() throws OAuthProblemException, OAuthSystemException {
        this.validators.put(GrantType.PASSWORD.toString(), PasswordValidator.class);
        this.validators.put(GrantType.CLIENT_CREDENTIALS.toString(), ClientCredentialValidator.class);
        this.validators.put(GrantType.AUTHORIZATION_CODE.toString(), CustomAuthorizationCodeValidator.class);
        this.validators.put(GrantType.REFRESH_TOKEN.toString(), RefreshTokenValidator.class);
        String requestTypeValue = this.getParam("grant_type");
        if (OAuthUtils.isEmpty(requestTypeValue)) {
            throw OAuthUtils.handleOAuthProblemException("Missing grant_type parameter value");
        } else {
            Class<? extends OAuthValidator<HttpServletRequest>> clazz = (Class)this.validators.get(requestTypeValue);
            if (clazz == null) {
                throw OAuthUtils.handleOAuthProblemException("Invalid grant_type parameter value");
            } else {
                return (OAuthValidator)OAuthUtils.instantiateClass(clazz);
            }
        }

    }
}
